<template>
  <div class="login">
    <div class="loginImg">
      <img src="../images/loginImg.png" alt="" />
    </div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      class="demo-ruleForm"
      :rules="rules"
      @keyup.enter="onSubmit"
    >
      <el-form-item label="请输入用户名:" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="请输入密码:&nbsp;&nbsp;&nbsp;" prop="pwd">
        <el-input v-model="ruleForm.pwd" />
      </el-form-item>
      <div class="btn">
        <el-button type="primary" @click="onSubmit">登录</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { notiFication } from "@/utils/message.js";
import { setToken } from "@/utils/setToken.js";
import { userLogin } from "@/api/UserData.js";
const router = useRouter();

//定义token
const token = ref("");

//ruleForm存储用户名和密码
const ruleForm = reactive({
  name: "",
  pwd: "",
});

//ruleFormRef存储form表单实例
const ruleFormRef = ref(null);

const rules = reactive({
  name: [
    {
      required: true,
      trigger: "blur",
      message: "请输入正确的用户名",
    },
  ],
  pwd: [
    {
      required: true,
      trigger: "blur",
      message: "请输入密码",
    },
  ],
});

/**
 * onSubmit
 * 表单校验函数 校验是否输入用户名和密码
 */
function onSubmit() {
  //表单校验函数
  if (
    ruleFormRef.value.validate(async () => {
      if (ruleForm.name !== "" && ruleForm.pwd !== "") {
        const res = await userLogin(ruleForm.name, ruleForm.pwd);
        token.value = res.data;
        if(res.code !== 2111){
          setToken(token.value);
          notiFication();
          router.push("/");
        }else{
          notiFication('用户名或者密码错误' , 'error')
        }
      }
    })
  );
}
</script>

<style lang="less" scoped>
.login {
  width: 1044px;
  height: 537px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  .loginImg {
    width: 479px;
    height: 388px;
  }

  .btn {
    button {
      width: 296px;
      height: 32px;
      margin-left: 10px;
    }
  }
}
</style>
